package com.guardian.buffer;

import com.guardian.command.Command;
import com.guardian.entity.GuardianObject;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 守护对象池
 * @author: huwei
 * @date: 2019/10/10 16:47
 * @version: 1.0.0
 */
public class GuardianObjectBuffer {
    /**
     * 守护对象池
     * key为守护对象的名称，即守护对象不能重复
     */
    private static final Map<String , GuardianObject> guardianObjectMap = new ConcurrentHashMap<>(16);

    /**
     * 守护对象池是否发生改变
     */
    private static AtomicBoolean change = new AtomicBoolean(false);

    public static final boolean contains(String guardianName){
        return guardianObjectMap.containsKey(guardianName);
    }

    public static final void add(GuardianObject guardianObject){
        guardianObjectMap.put(guardianObject.getName() ,guardianObject);
        change.set(true);
    }

    public static final GuardianObject remove(String guardianName){
        change.set(true);
        return guardianObjectMap.remove(guardianName);
    }

    public static final void clear(){
        change.set(true);
        guardianObjectMap.clear();
    }

    public static final boolean isChanged(){
        return change.get();
    }

    public static final Map<String , GuardianObject> copyBufferAndResetChange(){
        Map<String ,GuardianObject> copier = new ConcurrentHashMap<>(guardianObjectMap.size());
        copier.putAll(guardianObjectMap);
        change.set(false);
        return copier;
    }

    public static final Map<String , GuardianObject> copyBuffer(){
        Map<String ,GuardianObject> copier = new ConcurrentHashMap<>(guardianObjectMap.size());
        copier.putAll(guardianObjectMap);
        return copier;
    }

    public static final String listGuardianObject(){
        Map<String ,GuardianObject> copier = copyBuffer();
        StringBuffer sb = new StringBuffer();
        copier.forEach((k,v)->{
            sb.append("application name: ").append(k).append(Command.LINE_BREAK);
            sb.append("\tprobe command: ").append(v.getDetectionCommand()).append(Command.LINE_BREAK);
            sb.append("\tstart command: ").append(v.getStartCommand()).append(Command.LINE_BREAK);
            sb.append("\trestart success count: ").append(v.getStartSuccessCount()).append(Command.LINE_BREAK);
            sb.append("\trestart fail count: ").append(v.getStartFailCount()).append(Command.LINE_BREAK);
        });
        return sb.toString();
    }
}
